package org.jflame.auth.authz;

import org.jflame.commons.util.CollectionHelper;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * 表示一个同一类型的权限集合
 * 
 * @author charles.zhang
 * @param <T>
 */
public class PermitSet<T extends Permit> implements Serializable {

    private static final long serialVersionUID = -181460303662092829L;
    private final Set<T> permset;

    public PermitSet() {
        permset = new HashSet<>();
    }

    public PermitSet(Collection<T> c) {
        if (c == null) {
            throw new IllegalArgumentException("'c' must not be null");
        }
        permset = new HashSet<>(c.size());
        permset.addAll(c);
    }

    public void add(T p) {
        permset.add(p);
    }

    public void addAll(Collection<T> c) {
        if (CollectionHelper.isNotEmpty(c)) {
            permset.addAll(c);
        }
    }

    public boolean implies(T p) {
        for (T thisPermission : permset) {
            if (thisPermission.implies(p)) {
                return true;
            }
        }
        return false;
    }

    public boolean implies(final Collection<T> c) {
        if (CollectionHelper.isEmpty(c)) {
            return false;
        }
        for (T thisPermit : permset) {
            for (T thatPermit : c) {
                if (thisPermit.implies(thatPermit)) {
                    return true;
                }
            }
        }
        return false;
    }

    public final Set<T> getPermissions() {
        return permset;
    }

    public void setPermissions(Set<T> _permissions) {
        addAll(_permissions);
    }

    public Iterator<T> iterator() {
        return permset.iterator();
    }

    public boolean isEmpty() {
        return permset.isEmpty();
    }

}
